package org.suanfaTranning.ST200_Chatpter1_LineTable_HashTable_String.array;

import org.jikeshijian.Solution;

import java.util.Arrays;
import java.util.HashSet;

/**
 * @Auther: qingle
 * @Date: 2024/9/11-17:11
 * @Description:
 * @version: 1.0
 */
public class Solution_lengthOfLongestSubstring2 {
	public static int lengthOfLongestSubstring(String s) {
				int res = 0; // 最长子串的计算结果
				int[] lastIndex = new int[128]; // 存储每个字符最后一次出现的索引，初始化为-1
				for (int i = 0; i < lastIndex.length; i++) {
					lastIndex[i] = -1;
				}
				int left = 0; // 子串起始索引
				for (int right = 0; right < s.length(); right++) { // 遍历字符串的所有字符
					char c = s.charAt(right);
					// 如果字符已出现，则移动左指针到上次出现的下一个索引
					left = Math.max(left, lastIndex[c] + 1);
					// 记录当前字符的索引
					lastIndex[c] = right;
					// 计算当前子串的长度，并更新结果
					res = Math.max(res, right - left + 1);
				}
				return res;
			}

		public static void main(String[] args) {
			Solution_lengthOfLongestSubstring2 solution = new Solution_lengthOfLongestSubstring2();
			String input1 = "abcabcbb";
			System.out.println("Input: \"" + input1 + "\", Output: " + Solution_lengthOfLongestSubstring2.lengthOfLongestSubstring(input1));

			String input2 = "bbbbb";
			System.out.println("Input: \"" + input2 + "\", Output: " + Solution_lengthOfLongestSubstring2.lengthOfLongestSubstring(input2));

			String input3 = "pwwkew";
			System.out.println("Input: \"" + input3 + "\", Output: " + Solution_lengthOfLongestSubstring2.lengthOfLongestSubstring(input3));
		}
	}